<template>
  <div class="userGroup-form">
    <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
      <el-form-item label="名称" prop="title">
        <el-input v-model="formData.title" clearable></el-input>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input clearable type="number" v-model="formData.sort"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')">保存</el-button>
        <el-button @click="resetForm('formData')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'UserGroupForm',
  props: {
    dataId: String,
    dialogFormVisible: Boolean
  },
  data() {
    return {
      adjuncts: [],
      formData: {
        title: null,
        sort: null
      },
      limit: 1,
      rules: {
        title: [
          { required: true, message: '请输入版块名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.handleFormVisible()
  },
  watch: {
    dialogFormVisible(newVal, oldVal) {
      this.handleFormVisible()
    }
  },
  methods: {
    handleRemoveImg() {
      this.formData.pictureCover = null
    },
    handleFormVisible() {
      this.adjuncts = []
      //异步更新DOM
      this.$nextTick(() => {
        //清除表单验证
        this.$refs['formData'].clearValidate()
      })
      if (this.dataId == null) {
        this.formData = {
          title: null,
          sort: null
        }
      } else {
        //异步获取获取详情数据
        this.getDataById(this.dataId)
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$store
            .dispatch('userGroup/createOrUpdate', this.formData)
            .then(res => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$emit('handleDialog')
            })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getDataById(dataId) {
      this.$store.dispatch('userGroup/getByIdMoreDetail', dataId).then(res => {
        this.formData = res
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

